<template>
  <div>
    <!-- 三级分类 -->
    <Category :scene="scene" />
    <el-card class="margin-small">
      <div v-show="scene === 0">
        <el-button @click="addSpu" type="primary"
                   size="default"
                   icon="Plus"
                   :disabled="!categoryStore.c3Id">添加SPU</el-button>
        <el-table class="margin-small" border :data="records">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="SPU名称" prop="spuName"></el-table-column>
          <el-table-column label="SPU描述" prop="description" show-overflow-tooltip></el-table-column>
          <el-table-column label="SPU操作" align="center" width="270px">
            <template #="{ row }">
              <el-button @click="addSku(row)" type="primary" size="small" icon="Plus" title="添加SKU"></el-button>
              <el-button @click="updateSpu(row)" type="warning" size="small" icon="Edit" title="修改SPU"></el-button>
              <el-button @click="findSku(row)" type="info" size="small" icon="View" title="查看SKU列表"></el-button>
              <el-popconfirm :title="`确定删除${row.spuName}?`" width="200px" @confirm="deleteSpu(row.id)">
                <template #reference>
                  <el-button type="danger" size="small" icon="Delete" title="删除SPU"></el-button>
                </template>
              </el-popconfirm>


            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]"
                       background layout=" prev, pager, next, jumper,->,total, sizes" :total="total"
                       @current-change="getHasSpu"
                       @size-change="changeSize">
        </el-pagination>
      </div>
      <!-- 添加和修改SPU的子组件 -->
      <SpuForm ref="spu" v-show="scene === 1" @changeScene="changeScene" />
      <!-- 添加SKU的子组件 -->
      <SkuForm ref="sku" v-show="scene === 2" @changeScene="changeScene" />
      <el-dialog
                 title="SKU列表"
                 v-model="isShowSkuList">
        <el-table border :data="skuArr">
          <el-table-column label="名称" prop="skuName"></el-table-column>
          <el-table-column label="价格" prop="price"></el-table-column>
          <el-table-column label="重量" prop="weight"></el-table-column>
          <el-table-column label="图片">
            <template #="{ row }">
              <img :src="row.skuDefaultImg" style="width: 100px;height: 100px;">
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onBeforeUnmount } from "vue";
// 引入api
import { reqDeleteSpu, reqHasSpu, reqSkuList } from "@/api/product/spu/index";
// 引入ts类型
import type {
  HasSpuResponseData,
  Records,
  SPUData,
  SkuData,
  SkuInfoData,
} from "@/api/product/spu/type";
// 引入组件
import SpuForm from "./spuForm.vue";
import SkuForm from "./skuForm.vue";
// 引入分类相关二级仓库
import useCategoryStore from "@/store/modules/category";
import { ElMessage } from "element-plus";
// 获取分类相关二级仓库
const categoryStore = useCategoryStore();
// 控制场景切换
const scene = ref<number>(0);
// 分页器默认页码
const currentPage = ref<number>(1);
// 分页器默认数据量
const pageSize = ref<number>(3);
// 存储已有的SPU的数据
const records = ref<Records>([]);
// 存储SPU的总量
const total = ref<number>(0);
// 获取子组件实例
const spu = ref<any>();
const sku = ref<any>();
const skuArr = ref<SkuData[]>([])
const isShowSkuList = ref<boolean>(false);

// 监听三级分类id的变化
watch(
  () => categoryStore.c3Id,
  () => {
    // 保证存在三级分类ID
    if (!categoryStore.c3Id) return;
    getHasSpu();
  },
);

// 获取某个三级分类下的所有SPU
const getHasSpu = async (pager = 1) => {
  // 默认修改当前的页码为1
  currentPage.value = pager;
  const result: HasSpuResponseData = await reqHasSpu(
    currentPage.value,
    pageSize.value,
    categoryStore.c3Id,
  );
  if (result.code === 200) {
    records.value = result.data.records;
    total.value = result.data.total;
  }
};
// 分页器下拉菜单发生变化的时候出发
const changeSize = () => {
  getHasSpu();
};

// 添加新的SPU按钮的回调
const addSpu = () => {
  // 切换场景
  scene.value = 1;
  spu.value.initAddSpu(categoryStore.c3Id);
};

// 修改已有的SPU按钮的回调
const updateSpu = (row: SPUData) => {
  // 切换场景
  scene.value = 1;
  spu.value.initHasSpuData(row);
};

// 查看所有sku
const findSku = async (row: SPUData) => {
  const result: SkuInfoData = await reqSkuList(row.id as number)
  console.log(result)
  if (result.code === 200) {
    skuArr.value = result.data;
    isShowSkuList.value = true
  }
}

// 删除已有的spu
const deleteSpu = async (id: number) => {
  const result: any = await reqDeleteSpu(id)
  if (result.code === 200) {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    getHasSpu(records.value.length > 1 ? currentPage.value : currentPage.value - 1);
  } else {
    ElMessage({
      message: result.data,
      type: "error",
    });
  }
}

// 子组件SpuForm 绑定自定义事件,让子组件通知父组件切换场景
const changeScene = (obj: any) => {
  // 子组件SpuForm 点击取消按钮,展示场景 0
  scene.value = obj.flag;
  if (obj.params === "update") {
    // 刷新数据，留在当前页
    getHasSpu(currentPage.value);
  } else {
    // 刷新数据
    getHasSpu();
  }
};

// 添加SKU按钮的回调
const addSku = (row: SPUData) => {
  // 切换场景
  scene.value = 2;
  // 调用子组件SkuForm的initHasSpuData方法，初始化数据
  sku.value.initSkuData(categoryStore.c1Id, categoryStore.c2Id, row);
};

// 组件销毁前，清空分类仓库中数据
onBeforeUnmount(() => {
  // 仓库方法 $reset() 重置仓库中的数据
  categoryStore.$reset();
});
</script>

<style scoped lang="scss">
.margin-small {
  margin: 10px 0;
}
</style>
